package handle

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/huangxinbo/xcas/internal/app/base"
	"gitee.com/huangxinbo/xcas/internal/asynq_handle_routes"
	"gitee.com/huangxinbo/xcas/internal/model"
	"gitee.com/huangxinbo/xcas/internal/service"
	"gitee.com/huangxinbo/xcas/pkg/mail"
	"github.com/hibiken/asynq"
)

type EmailHandle struct {
	base    *base.Base
	service *service.Service
}

func NewEmailHandle(base *base.Base, service *service.Service) *EmailHandle {
	return &EmailHandle{
		base:    base,
		service: service,
	}
}

func (c *EmailHandle) HandleEmailRegisterVerification(ctx context.Context, t *asynq.Task) error {
	type CombinedPayload struct {
		Common asynq_handle_routes.RouteCommonPayload                    `json:"common"`
		Data   asynq_handle_routes.RouteEmailRegisterVerificationPayload `json:"data"`
	}
	var p CombinedPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}

	renderData := mail.RenderData{
		Subject: c.base.I18n.T("Welcome to join us - please verify your email"),
		ToEmail: p.Data.ToEmail,
		Data: model.RegisterVerification{
			VerificationLink: p.Data.VerificationLink,
		},
	}

	return c.base.Mail.SendEmail("register_verification.html", renderData)
}

func (c *EmailHandle) HandleEmailForgotVerification(ctx context.Context, t *asynq.Task) error {
	type CombinedPayload struct {
		Common asynq_handle_routes.RouteCommonPayload                  `json:"common"`
		Data   asynq_handle_routes.RouteEmailForgotVerificationPayload `json:"data"`
	}
	var p CombinedPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}

	renderData := mail.RenderData{
		Subject: c.base.I18n.T("Forgot password - please verify your email"),
		ToEmail: p.Data.ToEmail,
		Data: model.RegisterVerification{
			VerificationLink: p.Data.VerificationLink,
		},
	}

	return c.base.Mail.SendEmail("forgot_verification.html", renderData)
}
